<template>
    <base-breadcrumb title="危大工程范围">
            <searchData
                    :search-data="searchArr"
                    @search="search"
            />
        <a-card>
            <a-spin :spinning="loading1">
            <a-tabs v-model:activeKey="activeKey" @change="tabTopChange">
                <a-tab-pane :key="item.projectTypeId"
                            :tab="item.projectTypeName"
                            v-for="item in qualityTypes"></a-tab-pane>
            </a-tabs>
            </a-spin>
            <a-row
                    :gutter="10"
                    :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 345px); overflow: auto'"
            >
                <a-col :span="4" style="height: 100%">
                    <div style="height: 100%;border-right: 1px solid rgba(215, 215, 215, 1);padding-right: 10px;width: 100%;overflow: hidden;box-sizing: border-box">
                        <a-spin :spinning="loading2" style="height: 100%;">
                                <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange" />
                                <a-tree
                                        :selectedKeys.sync="selectedKeys"
                                        :expanded-keys="expandedKeys"
                                        :auto-expand-parent="autoExpandParent"
                                        :tree-data="gData"
                                        :replaceFields="{children:'children', title:'name', key:'id' }"
                                        @expand="onExpand"
                                        @select="selectTreeNode"
                                        :style="'maxHeight: calc('+GET_REDRESS_PERCENTAGE+'vh - 420px); overflow-y: auto'"
                                >
                                    <template slot="title" slot-scope="{ name, status }">
                                        <div class="ellipsis" :title="name">
                                        <span v-if="name.indexOf(searchValue) > -1">
                                          {{ name.substr(0, name.indexOf(searchValue)) }}
                                          <span style="color: #f50">{{ searchValue }}</span>
                                          {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                                        </span>
                                        <span v-else>{{ name }}</span>
                                        <span style="color: #ff4d4f">{{!status? '（停用）': ''}}</span>
                                        </div>
                                    </template>
                                </a-tree>
                        <div style="display: flex;justify-content: space-around;margin-top: 10px" v-if="hideBuquBtn()" >
                            <a-button type="primary" @click="openNodeModal(1)" size="small" v-btn-permission="'tm_048_add_01'">新增</a-button>
                            <a-button type="primary" @click="openNodeModal(2)" size="small" :disabled="isRoot" v-btn-permission="'tm_048_edi_02'">编辑</a-button>
                            <a-button  v-if="!selectOrg.status" @click="updateStatusLargeDangerConfig" size="small" :disabled="isRoot" v-btn-permission="'tm_048_sta_04'">启用</a-button>
                            <a-button type="danger" @click="updateStatusLargeDangerConfig" v-else size="small" :disabled="isRoot" v-btn-permission="'tm_048_sto_03'">停用</a-button>
                        </div>
                        </a-spin>
                    </div>
                </a-col>
                <a-col :span="20">
                    <a-tabs v-model:activeKey="projectType" @change="projectTypeChange">
                        <a-tab-pane key="1" tab="危大工程">
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="超危大工程" ></a-tab-pane>
                    </a-tabs>
                    <div class="mb10" v-btn-permission="'tm_048_add_05'">
                        <a-button type="primary" @click="addDes" :disabled="loading1 || loading2 || !isLastNode">添加范围描述</a-button>
                    </div>
                    <list-table
                            ref="table"
                            row-key="id"
                            :columns="columns"
                            :request="loadData"
                            :is-init="false"
                            :pageKeys="['pageNum', 'pageSize', 'total']"
                    >
                        <template
                                slot="enable"
                                slot-scope="text"
                        >
                            {{ text ? '可用' : '不可用' }}
                        </template>
                        <template slot="action" slot-scope="text,record">
                            <MoreButton>
                                <a @click="editDesc(record, 'view')" v-btn-permission="'tm_048_loo_06'">查看</a>
                                <a @click="editDesc(record, 'edit')" v-btn-permission="'tm_048_edi_07'" v-if="hideBuquBtn()">编辑</a>
                            </MoreButton>
                        </template>
                    </list-table>
                </a-col>
            </a-row>
        </a-card>
        <a-modal v-model="nodeVisible"
                 :title="nodeTitle"
                 @ok="handleOk" okText="提交"
                 width="600px"
                 :confirmLoading="loadingBtn1">
            <a-form-model
                    :model="form"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 14 }"
            >
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="父节点：">
                            <a-input
                                    disabled
                                    v-model="form.parentName"/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-model-item  label="子节点：" class="requiredFormItem">
                            <a-input
                                    v-model="form.name" :maxLength="20" placeholder="请输入子节点"/>
                        </a-form-model-item>
                    </a-col>
                </a-row>

            </a-form-model>
        </a-modal>
        <a-modal v-model="desVisible" :title="desTitle" width="70%" @cancel="cancel">
            <a-form-model
                    :model="form"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 14 }"
            >
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="范围描述：" class="requiredFormItem">
                            <a-textarea
                                    :disabled="disabled"
                                    v-model="row.desc"
                                    placeholder="请输入范围描述"
                                    :auto-size="{ minRows: 3, maxRows: 5 }"
                                    :maxLength="200"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item label="状态：" class="requiredFormItem">
                            <a-select v-model="row.status" style="width: 120px" :disabled="disabled" placeholder="请选择">
                                <a-select-option :value="1">
                                    可用
                                </a-select-option>
                                <a-select-option :value="0">
                                    不可用
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                </a-row>

            </a-form-model>
            <div slot="footer">
                <a-button @click="cancel">取消</a-button>
                <a-button type="primary" @click="handleDescOk" v-if="!disabled" :loading="loadingBtn2">提交</a-button>
            </div>
        </a-modal>
    </base-breadcrumb>
</template>

<script>
  import { getProjectTypes } from '@/api/project/projects'
  import { getLargeDangerConfigById,
    addLargeDangerConfig,
    editLargeDangerConfig,
    updateStatusLargeDangerConfig,
    getPageLargeDangerDescConfig,
    addLargeDangerDescConfig,
    editLargeDangerDescConfig
  } from '@/api/technology'
  import {mapGetters } from 'vuex'
  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.id;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  export default {
    name: 'DangerousBigProject',
    data() {
      return {
        isLastNode: false,
        isRoot: true,
        loading1: false,
        loading2: false,
        loadingBtn1: false,
        loadingBtn2: false,
        forceRender: true,
        disabled: false,
        desVisible: false,
        desTitle: '添加范围描述',
        row: {
          desc: '',
          status: null
        }, // 当前列的数据
        projectType: '1',
        nodeVisible: false,
        nodeTitle: '新增节点',
        activeKey: '',
        query: {},
        form: {
          parentName: '',
          name: null
        },
        rules: {},
        searchArr: [
          {
            name: '范围描述',
            value: 'desc',
            type: 'input'
          },
        ],
        columns: [
          {
            title: '范围描述',
            dataIndex: 'desc',
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'enable' },
            width: 120,
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            scopedSlots: { customRender: 'action' }
          }
        ],
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        selectedKeys: [],
        selectOrg: {},
        gData: [],
        dataList: [],
        qualityTypes: [],
        nodeId: '', // 节点id
        type: 1, // 1为新增 2为编辑
        listData: [],
        listData2: []
      }
    },
    computed: {
      ...mapGetters(['GET_REDRESS_PERCENTAGE'])
    },
    mounted() {
      this.getProjectTypes()
    },
    methods: {
      handleDescOk() {
        if(!this.row.desc || this.row.status === null) {
          this.$message.warning('请填写完所有必填项信息')
          return
        }
        const data = {
          ...this.row,
          largeDangerId: this.selectOrg.id ,
          projectType: this.projectType,
        }
        this.loadingBtn2 = true
        if(this.row.id) {
          editLargeDangerDescConfig(data).then(res=>{
            this.desVisible = false
            this.$message.success('修改成功')
            this.loadingBtn2 = false
              this.$refs.table.refresh(true)
          })
        } else {
          addLargeDangerDescConfig(data).then(res=>{
            this.desVisible = false
            this.loadingBtn2 = false
            this.$message.success('添加成功')
              this.$refs.table.refresh(true)
          })
        }
      },
      addDes() {
        if(this.selectOrg.children&&this.selectOrg.children.length>0) {
          this.$message.warning('请在节点最末级添加范围描述')
          return
        }
        this.disabled = false
        this.desTitle = '添加范围描述'
        this.row = {
          desc: '',
          status: null
        }
        this.desVisible = true
      },
      editDesc(row, type) {
        this.disabled = type === 'view'
        this.desTitle = type === 'view' ? '查看范围描述':'编辑范围描述'
        this.row = { ...row, status: row.status ? 1 : 0 }
        this.desVisible = true
      },
      cancel() {
        this.desVisible = false
      },
      projectTypeChange() {
        this.$refs.table.refresh(true)
      },
      // 点击添加节点确定按钮
      handleOk() {
        if(!this.form.name) {
          this.$message.warning('请填写完所有必填项信息')
          return
        }
        let data = {
          typeId: this.activeKey,
          parentId:  this.type === 1 ?this.selectOrg.id : this.selectOrg.parentId,
          name: this.form.name
        }
        this.loadingBtn1 = true
        if(this.type ===1) {
          addLargeDangerConfig(data).then(res=>{
            this.nodeVisible = false
            this.loadingBtn1 = false
            this.$message.success('添加成功')
            this.isLastNode = false
            this.getLargeDangerConfigById(this.activeKey)
          })
        } else {
          data.id = this.selectOrg.id
          editLargeDangerConfig(data).then(res=>{
            this.nodeVisible = false
            this.loadingBtn1 = false
            this.selectOrg.name = this.form.name
            this.$message.success('修改成功')
            this.getLargeDangerConfigById(this.activeKey)
          })
        }
      },
      // g更新节点状态
      updateStatusLargeDangerConfig() {
        const fn = () => {
          this.loading2 = true
          const data = {
            "id": this.selectOrg.id,
            "name": this.selectOrg.name,
            "parentId": this.selectOrg.parentId,
            "status": !this.selectOrg.status,
            "typeId": this.selectOrg.typeId
          }
          updateStatusLargeDangerConfig(data).then(res=>{
            this.$message.success(!this.selectOrg.status ? '启用成功': '停用成功')
            this.selectOrg.status = !this.selectOrg.status
            this.getLargeDangerConfigById(this.activeKey)
          })
        }
        if(this.selectOrg.status) {
          this.$confirm({
            title: '提示',
            content: '停用该节点时会同时停用该节点下的范围描述，确认是否停用？',
            onOk() {
              fn()
            },
            onCancel() {},
          });
        } else {
          fn()
        }
      },
      // 打开节点弹窗
      openNodeModal(type) {
        this.type = type
        if(type === 1) {
          if(this.listData.length>0 || this.listData2.length>0) {
            this.$message.warning('该节点中已存在范围描述，若继续添加子节点，则不能使用该节点中的范围描述')
          }
          this.form.parentName = this.selectOrg.name;
          this.form.name = "";
          this.nodeTitle = '新增节点'
        } else {
          this.nodeTitle = '编辑节点'
          this.form.parentName = this.selectOrg.parentName;
          this.form.name = this.selectOrg.name
        }
        this.nodeVisible = true
      },
      // 获取树
      getLargeDangerConfigById(id, isInit = false) {
        getLargeDangerConfigById({ typeId:id }).then(res=>{
          this.dataList = []
          this.generateList(res.data)
          this.gData = res.data;
          this.loading2 = false
          if(isInit) {
            this.isRoot = true
            this.selectedKeys = [this.gData[0].id]
            this.selectOrg = this.gData[0]
            this.form.parentName = this.selectOrg.name || '无'
            this.$nextTick(()=>{
              this.$refs.table.refresh(true)
              this.getPageLargeDangerDescConfig()
            })
          }
        })
      },
      // 获取工程类别
      getProjectTypes(isRefresh=false) {
        this.loading1 = true
        this.loading2 = true
        getProjectTypes().then((res) => {
          this.qualityTypes = res.data?.filter(i => i.status*1 === 1)
          this.loading1 = false
          if(isRefresh) {
            this.loading2 = false
          } else {
            this.activeKey = this.qualityTypes[0].projectTypeId
            this.getLargeDangerConfigById( this.activeKey, true)
          }
        })
      },
      loadData(parameter) {
        const requestParameters = Object.assign({}, parameter, {
          param: {
            largeDangerId: this.selectOrg.id ,
            projectType: this.projectType,
            ...this.query
          }
        })
       return getPageLargeDangerDescConfig(requestParameters).then(res=>{
           this.listData = res.data.list;
             res.data.totalSize = res.data.total
             return res
       })
      },
      getPageLargeDangerDescConfig(parameter) {
        const requestParameters = Object.assign({}, parameter, {
          param: {
            largeDangerId: this.selectOrg.id ,
            projectType: '2',
            ...this.query
          }
        })
       getPageLargeDangerDescConfig(requestParameters).then(res=>{
          this.listData2 = res.data.list;
        })
      },
      search(val) {
        this.query = val
        this.getProjectTypes(true)
        this.$refs.table.refresh(true)
      },
      tabTopChange(activeKey) {
        this.loading2 = true
        this.projectType = '1'
        this.getLargeDangerConfigById(activeKey, true)
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      onChange(e) {
        const value = e.target.value;
        const expandedKeys = this.dataList
          .map(item => {
            if (item.name.indexOf(value) > -1) {
              console.log(item.name,item.key)
              return getParentKey(item.key, this.gData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
      },
      selectTreeNode(selectedKeys, { node}) {
        this.selectedKeys = selectedKeys;
        this.selectOrg = {...node.dataRef, parentName: node.dataRef.parentId ? node.$parent.dataRef.name : '无'}
        if(node.dataRef.children&&node.dataRef.children.length) {
          this.isLastNode =false
        } else {
          this.isLastNode =true
        }
        if(node.dataRef.parentId) {
          this.isRoot = false
        } else {
          this.isLastNode =false
          this.isRoot = true
        }

        this.projectType = '1'
        this.$refs.table.refresh(true)
        this.getPageLargeDangerDescConfig()
      },
      generateList(data) {
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          node.scopedSlots = { title: 'title'}
          this.dataList.push(node);
          if (node.children&&node.children.length>0) {
            this.generateList(node.children);
          }
        }
      },
    }
  }
</script>

<style scoped>
    .ellipsis {
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        white-space: nowrap;
    }
</style>